from django.shortcuts import render
from .models import Doc
from django.http import FileResponse, Http404
from dj32_test.settings import dev
import requests
import logging
from django.utils.encoding import escape_uri_path

logger = logging.getLogger("django")
# Create your views here.
def document(request):
    docs = Doc.objects.only("title", "desc", "image_url", "file_url", "id").filter(is_delete=False)
    return render(request, 'doc/docDownload.html', {"docs": docs})


def document_download(request, doc_id):
    doc_obj = Doc.objects.only("file_url", "title").filter(is_delete=False, id=doc_id).first()
    # 表明文档是否存在
    if doc_obj:
        # 获取文件路径
        file_url = doc_obj.file_url
        # 拼接成完整的url
        # BASE_URL为自定义设置，表示网站的域名
        file_url = dev.BASE_SITE + file_url
        response = None
        try:
            # 使用requests获取文件请求对象
            # FileResponse会自动从response获取文件内容
            file_stream = requests.get(file_url, stream=True)
            response = FileResponse(file_stream)
        except requests.exceptions.ConnectionError as e:
            raise Http404("网络出现问题")
            logging.error(e)
            response.status_code = 'Connection Refused'


        # 取得文件的后缀名
        file_ext = file_url.split(".")[-1]
        if not file_ext:
            raise Http404("文件名异常")
        else:
            file_ext = file_ext.lower()
        # 检查文件后缀名，赋予对应的Content-Type
        if file_ext == "pdf":
            response["Content-Type"] = "application/pdf"
        elif file_ext == "doc":
            response["Content-Type"] = "application/msword"
        elif file_ext == "ppt" :
            response["Content-Type"] = "application/vnd.ms-powerpoint"
        else:
            raise Http404("文件格式错误")
        # 过滤文件名，去掉不安全的字符
        file_name = escape_uri_path(doc_obj.title + "." + file_ext)
        # 给用户提供一个默认的文件名，如果没有设置，则默认为“下载.ext”
        # 如果是attachment，就直接下载
        # 如果是inline，就在浏览器中打开
        # filename表示下载时的文件名，如果没有则是“下载.ext”
        response["Content-Disposition"] = "inline; filename={}".format(file_name)
        return response
    else:
        raise Http404("Doc Not Found")
